import React from "react";
import SearchHeader from "../../components/SearchHeader";
import { Flex ,Toast} from "antd-mobile";
import styles from "./index.module.css";
import Filter from "./components/Filter";
import { API } from "../../utils/api";
import {getCurentCity} from '../../utils'
import {
	List,
	AutoSizer,
	WindowScroller,
	InfiniteLoader,
} from "react-virtualized";
import HouseItem from "../../components/HouseItem";
import { BASE_URL } from "../../utils/url";
import Sticky from '../../components/sticky'
import NoHouse from "../../components/NoHouse";
// 获取当前城市定位信息
// const { label, value } = JSON.parse(localStorage.getItem("ytzf_city"));
class HouseList extends React.Component {
	state = {
		// 列表数据
		list: [],
		// 总条数
		count: 0,
		// 数据是否加载中
		isloading:false
	};
	// 初始化默认值
	label=''
	value=''
	//初始化filters
	filters = {};

	// 接收Filter组件中的筛选条件数据的
	onFilter = (filters) => {
		// 返回页面顶部
		window.scrollTo(0,0)

		this.filters = filters;
		// 调用获取房屋数据的方法
		this.searchHouseList();
	};

	// 用来获取房屋列表数据的方法
	async searchHouseList() {
		this.setState({
			isloading:true
		})
		// 开启loading
		Toast.loading('加载中...',0,null,false)
		const res = await API.get(`/houses`, {
			params: {
				cityId: this.value,
				...this.filters,
				start: 1,
				end: 20,
			},
		});
		const { list, count } = res.data.body;
		// 关闭loading
		Toast.hide()
		// 提示房源数量
		if(count){
			Toast.info(`共找到${count}套房源`,2,null,false)
		}else{

		}

		this.setState({
			list,
			count,
			isloading:false
		});
	}

	async componentDidMount() {
		const {label,value}=await getCurentCity()
		this.value=value
		this.label=label
		this.searchHouseList();
	}

	renderHouseList = ({
		key,
		index, //索引号
		style, //!!一定要给每一行添加该样式
	}) => {
		// 根据索引号来获取当前这一行的房屋数据
		const { list } = this.state;
		const house = list[index];
        // console.log('loading',house)
        // 判断house是否存在
        // 如果不存在就渲染一个loading元素

		if(!house){
            return (
                <div key={key} style={style}>
                    <p className={styles.loading}></p>
                </div>
            )
        }

		return (
			<HouseItem
				key={key}
				style={style}
				src={BASE_URL + house.houseImg}
				title={house.title}
				desc={house.desc}
				tags={house.tags}
				price={house.price}
			/>
		);
	};

	// 判断列表中的每一行数据 是否加载完毕
	isRowLoaded = ({ index }) => {
		return !!this.state.list[index];
	};

	// 用来获取更多房屋列表数据
	// 注意：该方法的返回值是一个promise对象
	// 并且这个对象应该在数据加载完成，来调用resolve让promise对象的状态为已完成
	loadMoreRows = ({ startIndex, stopIndex }) => {
		return new Promise((resolve) => {
			API.get(`/houses`, {
				params: {
					cityId: this.value,
					...this.filters,
					start: startIndex,
					end: stopIndex,
				},
			}).then((res) => {
				this.setState({
					list: [...this.state.list, ...res.data.body.list],
				});
				// 数据加载完成 调用resolve
				resolve();
			});
		});
	};

	// 渲染列表数据
	renderList=()=>{
		const {count,isloading}=this.state
		if(count===0&&!isloading){
			return <NoHouse>没有找到房源，请您换个搜索条件吧</NoHouse>
		}
		
		return(
			<InfiniteLoader
						isRowLoaded={this.isRowLoaded}
						loadMoreRows={this.loadMoreRows}
						rowCount={count}
			>
						{({ onRowsRendered, registerChild }) => (
							<WindowScroller>
								{({ height, isScrolling, scrollTop }) => (
									<AutoSizer>
										{({ width }) => (
											<List
												onRowsRendered={onRowsRendered}
												ref={registerChild}
												autoHeight //设置高度为windowScroll而最终渲染的列表高度
												width={width}
												height={height}
												rowCount={count}
												rowHeight={120}
												rowRenderer={this.renderHouseList}
												isScrolling={isScrolling}
												scrollTop={scrollTop}
											/>
										)}
									</AutoSizer>
								)}
							</WindowScroller>
						)}
					</InfiniteLoader>
		)
	}

	render() {
		const { count } = this.state;
		return (
			<div className="root">
				{/*顶部搜索导航  */}
				<Flex className={styles.header}>
					<i
						className="iconfont icon-back"
						onClick={() => {
							this.props.history.go(-1);
						}}
					></i>
					<SearchHeader cityName={this.label} className={styles.searchHeader} />
				</Flex>

				{/* 条件筛选栏 */}
				<Sticky height={40}>
				<Filter onFilter={this.onFilter} />
				</Sticky>

				{/* 房屋列表 */}
				<div className={styles.houseItems}>
					{/* 房屋列表内容 */}
					{this.renderList()}
				</div>
			</div>
		);
	}
}
export default HouseList;
